/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets.gp.patient;

import be.ugent.medirem.logic.GpRemote;
import be.ugent.medirem.logic.PatientRemote;
import be.ugent.medirem.persistence.entity.details.PatientDetails;
import be.ugent.medirem.persistence.entity.values.PatientValues;
import be.ugent.medirem.persistence.exception.EntityNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Simon
 */
public class AddPatientServlet extends HttpServlet {

    @EJB
    private GpRemote gpBean;
    @EJB
    private PatientRemote patientBean;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.getRequestDispatcher("/gp/patient/add.jsp").forward(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getUserPrincipal().getName();
        Long gpId = gpBean.getGpId(username);
        boolean validation = true;
        PatientValues p = (PatientValues) request.getAttribute("patient");
        Long pId = p.getId();
        if (pId != null) {
            try {
                PatientDetails p1 = patientBean.getPatientDetails(p.getId());
                p.setUsername(p1.getUsername());
                patientBean.updatePatient(p);
                request.getSession().setAttribute("flash", "Patient has been added to your list of patients");
            } catch (EntityNotFoundException ex) {
                Logger.getLogger(AddPatientServlet.class.getName()).log(Level.SEVERE, null, ex);
                validation = false;
            } catch (IllegalArgumentException ex) {
                Logger.getLogger(AddPatientServlet.class.getName()).log(Level.SEVERE, null, ex);
                validation = false;
            }
        } else {
            try {
                pId = patientBean.createPatient(p);
            } catch(Exception e) {
                validation = false;
            }
        }
        if (validation) {
            try {
                gpBean.addPatient(gpId, pId);
            } catch (EntityNotFoundException ex) {
                Logger.getLogger(AddPatientServlet.class.getName()).log(Level.SEVERE, null, ex);
                validation = false;
            } catch (IllegalArgumentException ex) {
                Logger.getLogger(AddPatientServlet.class.getName()).log(Level.SEVERE, null, ex);
                validation = false;
            } catch (Exception e) {
                // Duplicate key
                validation = false;
                request.setAttribute("flash", "Patient already registered with you");
            }
            if (validation && request.getSession().getAttribute("flash") == null) {
                request.getSession().setAttribute("flash", "Patient has been created and added to your list of patients");
            }
            if (validation)
                response.sendRedirect(request.getContextPath() + "/gp/patient/list");
        }
        if (!validation) {
            if (request.getAttribute("flash") == null)
                request.setAttribute("flash", "Input is invalid");
            request.setAttribute("patient", p);
            request.getRequestDispatcher("/gp/patient/add.jsp").forward(request, response);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
